import type { REPORT_FORM_ID, REPORT_STATUS } from '@/enum'
import { loadReportDataByReportId } from '@/api/modules/dataReport'
import type HandsonTable from 'handsontable'
import { ROUND_NUMBER } from './config'

export interface LoadReportResponse {
  /** 报表数据主键ID */
  id: number
  /** 子公司名称 */
  subsidiaryName: string
  /** 子公司所在区域 */
  subsidiaryRegion: string
  /** 社会信用代码 */
  socialCreditCode: string
  /** 报告所属年 */
  year: number
  /** 报告所属月 */
  month: number
  /** 报表状态 */
  status: REPORT_STATUS
  /** 前端报表数据-JSON */
  webReportData: string
  /** 前端报表格式-JSON */
  webReportFormat: string
}
export default function useReportDetail() {
  async function getReportDataById(dataId: number, formId?: REPORT_FORM_ID) {
    const { data } = await loadReportDataByReportId(
      dataId,
      formId,
    )
    return data as LoadReportResponse
  }

  function beforeChangeHook(exclude: ([number, number | string][]) | (() => [number, number | string][])) {
    const isExcluded = (row: number, prop: string) => {
      let e: [number, number | string][]
      if (typeof exclude === 'function') {
        e = exclude()
      }
      else {
        e = exclude
      }
      return e.some(([x, y]) => x === row && +y === +prop)
    }
    return function (changes: (HandsonTable.CellChange | null)[], source: HandsonTable.ChangeSource): boolean | void {
      if (source === 'edit') {
        changes.forEach(([row, prop, oldValue, newValue]: any, index) => {
          if (isExcluded(row, prop))
            return
          if (typeof newValue === 'string') {
            if (newValue === '') {
              return
            }
            if (newValue.trim().length > 15) {
              newValue = newValue.substring(0, 16)
            }
            let parsedValue = Number.parseFloat(newValue)
            if (!Number.isNaN(parsedValue)) {
              // 格式化数值为最多4位小数
              parsedValue = Number.parseFloat(parsedValue.toFixed(ROUND_NUMBER))
              console.log(`parseFloat(${newValue}) => ${parsedValue}`)
              // 更新 changes 数组中的值
              changes[index] = [row, prop, oldValue, parsedValue]
            }
            else {
              console.log(`parseFloat(${newValue}) => ${parsedValue}`)
              changes[index] = [row, prop, oldValue, parsedValue]
            }
          }
        })
      }
    }
  }
  return {
    getReportDataById,
    beforeChangeHook,
  }
}
